<?php

namespace App\Models;

use App\Observers\FangObserver;

class Fang extends Base
{
    //追加字段
    protected $appends = ['pic_url', 'pic_list','config_list','direction'];

    //让观察类引入到模型中进行观察
    protected static function boot()
    {
        parent::boot();
        self::observe(FangObserver::class);
    }

    //根据省或市或区的id返回对应的名称
    public function getAreaToName()
    {
        $area = City::where('id', $this->fang_province)->value('area');
        $area .= City::where('id', $this->fang_city)->value('area');
        $area .= City::where('id', $this->fang_region)->value('area');
        return $area;
    }

    //房源业主和房源信息之间的关系  房源属于房东
    public function owner()
    {
        return $this->belongsTo(Fangowner::class, 'fang_owner');
    }

    //房源属性展示
    public function getAttrIdToName($attr_id)
    {
        $name = '';
        if (strstr($attr_id, ',')) {
            //传过来的属性id有多个，中间以逗号隔开，在查询时使用where in
            $arr = Fangattr::whereIn('id', explode(',', $attr_id))->pluck('name')->toArray();
            $name = implode(',', $arr);
        } else {
            $name = Fangattr::where('id', $attr_id)->value('name');
        }
        return $name;
    }

    //房源是否推荐的访问器 返回一个html,所有在blade模版中要注意转义的问题
    public function getRecommendAttribute()
    {
        if ($this->is_recommend == '0') {
            return '<span class="label label-warning radius">不推荐</span>';
        } else {
            return '<span class="label label-success radius">推荐</span>';
        }
    }

    //配套设施访问器
    public function getConfigAttribute()
    {
        return explode(',', $this->fang_config);
    }

    //房源图片访问器
    public function getPicsAttribute()
    {
        $pic = trim($this->fang_pic, '#');
        return explode('#', $pic);
    }

    //推荐房源接口访问图片地址
    public function getPicUrlAttribute()
    {
        $pic = trim($this->fang_pic, '#');
        $arr = explode('#', $pic);
        return $this->domain . $arr[0];
    }

    //房源详情接口图片列表
    public function getPicListAttribute()
    {
        $domain = $this->domain;
        $pic = trim($this->fang_pic, '#');
        $arr = explode('#', $pic);
        return array_map(function ($item) use ($domain) {
            return $domain . $item;
        }, $arr);
    }
    //访问器 房源配套设施
    public function getConfigListAttribute(){
        $attr_id=$this->fang_config;
        //传过来的字段含多个id,中间逗号隔开 wherein 查询
        $arr=Fangattr::whereIn('id',explode(',',$attr_id))->pluck('name')->toArray();
        return $arr;
    }
    public function  getDirectionAttribute(){
        $attr_id=$this->fang_direction;
        return $data=Fangattr::where('id',$attr_id)->get(['name'])->toArray();
    }
}
